using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Linq;

namespace WebBrowser
{
    public class HistoryManager
    {
        private readonly string _historyFilePath;
        private List<HistoryItem> _historyItems;

        public HistoryManager()
        {
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var browserDataPath = Path.Combine(appDataPath, "CooBrowser");
            Directory.CreateDirectory(browserDataPath);
            _historyFilePath = Path.Combine(browserDataPath, "history.json");
            _historyItems = new List<HistoryItem>();
            LoadHistory();
        }

        public List<HistoryItem> GetHistory()
        {
            return _historyItems.OrderByDescending(h => h.VisitTime).ToList();
        }

        public List<HistoryItem> GetHistoryByDate(DateTime date)
        {
            return _historyItems
                .Where(h => h.VisitTime.Date == date.Date)
                .OrderByDescending(h => h.VisitTime)
                .ToList();
        }

        public void AddHistoryItem(string title, string url, string faviconUrl = "")
        {
            // Skip certain URLs
            if (string.IsNullOrEmpty(url) || 
                url.StartsWith("about:") || 
                url.StartsWith("edge://") || 
                url.StartsWith("chrome://"))
            {
                return;
            }

            // Check if URL already exists
            var existingItem = _historyItems.FirstOrDefault(h => h.Url.Equals(url, StringComparison.OrdinalIgnoreCase));
            if (existingItem != null)
            {
                // Update existing item
                existingItem.Title = title;
                existingItem.VisitTime = DateTime.Now;
                existingItem.VisitCount++;
                if (!string.IsNullOrEmpty(faviconUrl))
                {
                    existingItem.FaviconUrl = faviconUrl;
                }
            }
            else
            {
                // Add new item
                var historyItem = new HistoryItem(title, url, faviconUrl);
                _historyItems.Add(historyItem);
            }

            SaveHistory();
        }

        public void ClearHistory()
        {
            _historyItems.Clear();
            SaveHistory();
        }

        public void RemoveHistoryItem(string url)
        {
            _historyItems.RemoveAll(h => h.Url.Equals(url, StringComparison.OrdinalIgnoreCase));
            SaveHistory();
        }

        public List<HistoryItem> SearchHistory(string searchTerm)
        {
            if (string.IsNullOrEmpty(searchTerm))
                return GetHistory();

            return _historyItems
                .Where(h => h.Title.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ||
                           h.Url.Contains(searchTerm, StringComparison.OrdinalIgnoreCase))
                .OrderByDescending(h => h.VisitTime)
                .ToList();
        }

        private void LoadHistory()
        {
            try
            {
                if (File.Exists(_historyFilePath))
                {
                    var json = File.ReadAllText(_historyFilePath);
                    _historyItems = JsonSerializer.Deserialize<List<HistoryItem>>(json) ?? new List<HistoryItem>();
                }
            }
            catch (Exception)
            {
                _historyItems = new List<HistoryItem>();
            }
        }

        private void SaveHistory()
        {
            try
            {
                var json = JsonSerializer.Serialize(_historyItems, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_historyFilePath, json);
            }
            catch (Exception)
            {
                // Handle save error silently
            }
        }
    }
}